package com.asiainfo.indb.listener;

import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

/**
 * input框的占位符提示功能
 *
 * @author zym
 * @date 2019-10-17 21:24
 */
public class PlaceholderListener implements FocusListener {

    /**
     * 目标
     */
    private JTextField target;

    /**
     * 占位符
     */
    private volatile String placeholder;

    public PlaceholderListener(JTextField target, String placeholder) {
        this.target = target;
        this.placeholder = placeholder;
        this.target.setText(placeholder);
        this.target.setForeground(Color.GRAY);
    }

    @Override
    public void focusGained(FocusEvent e) {
        if (StringUtils.equals(placeholder, target.getText())) {
            target.setText("");
            target.setForeground(Color.BLACK);
        }
    }

    @Override
    public void focusLost(FocusEvent e) {
        if (StringUtils.isBlank(target.getText()) || StringUtils.equals(placeholder, target.getText())) {
            target.setText(placeholder);
            target.setForeground(Color.GRAY);
        } else {
            target.setForeground(Color.BLACK);
        }
    }

    /**
     * 刷新占位符
     */
    public void freshPlaceholder(String holder) {
        this.placeholder = holder;
        this.target.setText(holder);
    }

}